﻿using System;
using System.Collections.Generic;
using System.Text;

using iTool.SQL.Analysis.Context;
using iTool.SQL.Analysis.Context.Options;
using iTool.SQL.Analysis.Context.SQLWhereOptions;

using Microsoft.SqlServer.Management.SqlParser.SqlCodeDom;

namespace iTool.SQL.Analysis.WhereClause
{
    public class SqlScalarVariableRefExpressionAnalysis : SqlAnalysisBase
    {
        public SqlScalarVariableRefExpressionAnalysis(SqlAnalysisContext context) : base(context)
        {
        }

        public override void Analysis()
        {
            var variable = (SqlScalarVariableRefExpression)base.CodeObject;
            var where = (WhereOptions)base.WhereOptions;
            switch (base.CodeObject.Parent)
            {
                case var t when t is SqlSelectScalarExpression:
                    ((SqlSelectAnalysisContext)base.context).QueryFields.Add(new Context.Options.SQLFieldOptions
                    {
                        Value = variable.VariableName
                    });
                    break;
                default:

                    var valueOptions = new ValueOptions { ValueType = typeof(SqlParameterOption),Value = variable.VariableName };

                    if (base.WhereProperty != null)
                    {
                        if (base.WhereProperty is BetweenValueOptions between)
                        {
                            if (between.Start.ValueType == null)
                                between.Start = valueOptions;
                            else
                                between.End = valueOptions;
                        }
                    }
                    else
                    {
                        if (where.Right is ValueOptions[])
                            ((ValueOptions[])where.Right)[base.Index] = valueOptions;
                        else if (where.Left == null)
                            where.Left = valueOptions;
                        else if (where.Right == null)
                            where.Right = valueOptions;
                    }

                    //StringBuilder where = base.GetWhereBuilder();
                    //where.Append($"'{integer.Value}'");
                    return;
            }
        }

        public override bool Validation(SqlCodeObject codeObject) => true;
    }
}
